﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using D2DEngine;
using Microsoft.Xna.Framework;

namespace D2DEngine.AI
{
    public abstract class D2DBehavior
    {
        protected D2DSceneObject sceneObject;

        public D2DSceneObject SceneObject
        {
            get { return this.sceneObject; }
            set { this.sceneObject = value; }
        }

        public D2DBehavior() : base()
        {
        }

        public virtual void OnRegister()
        {
        }

        public abstract void Update(GameTime gameTime);

        /// <summary>
        /// Turns the entity towards a vector at the given speed.
        /// </summary>
        /// <param name="facePosition"></param>
        /// <param name="turnSpeed"></param>
        public void TurnToFace(Vector2 facePosition, float turnSpeed)
        {
            float x = facePosition.X - this.sceneObject.Position.X;
            float y = facePosition.Y - this.sceneObject.Position.Y;

            float desiredAngle = (float)Math.Atan2(y, x);
            float difference = WrapAngle(desiredAngle - (this.sceneObject.Rotation));

            difference = MathHelper.Clamp(difference, -turnSpeed, turnSpeed);
            this.sceneObject.Rotation = WrapAngle(this.sceneObject.Rotation + difference);
        }

        /// <summary>
        /// Returns the angle expressed in radians between -Pi and Pi.
        /// <param name="radians">the angle to wrap, in radians.</param>
        /// <returns>the input value expressed in radians from -Pi to Pi.</returns>
        /// </summary>
        public static float WrapAngle(float radians)
        {
            while (radians < -MathHelper.Pi)
            {
                radians += MathHelper.TwoPi;
            }

            while (radians > MathHelper.Pi)
            {
                radians -= MathHelper.TwoPi;
            }

            return radians;
        }



    }
}
